package com.fingard.dsp.bank.syncdata;

import java.util.Date;

import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDbHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.dbhelpers.SerializeHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;

public class SaveToDb {

	public HelperResp doSave(String pXml){
		HelperResp resp = new HelperResp();
		resp.isCompleted = false;
		try{
			String itemPath = "/ATSYH/TransReq/TransParam/item";
			XmlTextReader reader = new XmlTextReader(pXml);
			String dataType = reader.getSimpleTextNotNull("DataType");
			if("receipt".equalsIgnoreCase(dataType)){
				if(reader.read(itemPath)){
					if(ReceiptDbHelper.saveReceiptMappingByXe(reader.readedXElement)){
						resp.isCompleted = true; 
					}else{
						resp.appendMsgLn("receipt执行SaveToDb失败");
					}
				}else{
					resp.appendMsgLn("不存在节点"+itemPath);
				}
			}else if("receiptPro".equalsIgnoreCase(dataType)){
				ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
				try{
					String strBusDate = reader.getSimpleTextNotNull("BusDate");
					Date busDate = DateHelper.convertToDateExtra(strBusDate);
					String tenant = reader.getSimpleTextNotNull("Tenant");
					receiptHelper = new ReceiptDataHelper(tenant, busDate);
					int svCount = 0;
					int rdCount = 0;
					while(reader.read(itemPath)){
						rdCount++;
						ReceiptData eachData = new ReceiptData();
						SerializeHelper.loadObjectFromXeAttr(reader.readedXElement, eachData);
						if("102".equals(eachData.bank)){
							svCount += receiptHelper.insertIfNotExistByReceiptNo(eachData, false);
						}else{
							svCount += receiptHelper.insertIfNotExist(eachData);
						}
					}
					if(svCount == rdCount){
						resp.isCompleted = true; 
					}else{
						resp.appendMsgLn("receiptPro执行SaveToDb失败，应保存"+rdCount+"条，实际保存"+svCount+"条");
					}
				}catch(Exception ex){
					resp.appendMsgLn("receiptPro执行SaveToDb异常："+LogHelper.getStackTrace(ex));
				}finally{
					receiptHelper.close();
				}
			}else{
				resp.appendMsgLn("未知的DataType："+dataType);
			}
		}catch(Exception ex){
			resp.appendMsgLn("receipt执行SaveToDb异常："+LogHelper.getStackTrace(ex));
		}
		return resp;
	}
}
